import requests
import json
import os

def ask_deepseek(user_question,
                 system_prompt=
                 "驾校管理系统助手。简洁回答，100字内，只回答要点。无关问题请拒绝回答。"):
    """
    向DeepSeek API发送请求并获取回复
    """
    # 1. API endpoint 和 Key (从环境变量读取，不要硬编码在代码里！)
    api_url = "https://api.deepseek.com/v1/chat/completions"
    api_key = os.getenv("DEEPSEEK_API_KEY") # 强烈推荐使用环境变量
    if not api_key:
        raise ValueError("请设置 DEEPSEEK_API_KEY 环境变量")

    # 2. 构建请求头
    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json"
    }

    # 3. 构建请求数据
    payload = {
        "model": "deepseek-chat", # 根据实际模型名修改
        "messages": [
            {"role": "system", "content": system_prompt},
            {"role": "user", "content": user_question}
        ],
        "temperature": 0.7, # 控制创造性，驾校问答建议较低值以保证准确
        "max_tokens": 200,
    }

    # 4. 发送请求
    try:
        response = requests.post(api_url, headers=headers, data=json.dumps(payload))
        response.raise_for_status() # 检查请求是否成功

        # 5. 解析返回的JSON数据，提取AI回复
        response_data = response.json()
        ai_reply = response_data['choices'][0]['message']['content']
        return ai_reply

    except requests.exceptions.RequestException as e:
        # 处理网络或API错误
        print(f"Error calling DeepSeek API: {e}")
        return "抱歉，AI助手暂时无法服务，请稍后再试。"
